package com.xuchy.algorithm;

import com.google.common.collect.Range;
import io.shardingsphere.api.algorithm.sharding.RangeShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.RangeShardingAlgorithm;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * @author xuchy
 * @Date 2019/11/5 23:22
 */
public class TableRangeShardAlgorithm implements RangeShardingAlgorithm<String> {

    private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<String> rangeShardingValue) {
        System.out.println("范围-*-*-*-*-*-*-*-*-*-*-*---------------" + availableTargetNames);
        System.out.println("范围-*-*-*-*-*-*-*-*-*-*-*---------------" + rangeShardingValue);
        //物理表名集合
        Collection<String> tables = new LinkedHashSet<>();
        //逻辑表名
        String logicTableName = rangeShardingValue.getLogicTableName();
        //分片键的值
        Range<String> valueRange = rangeShardingValue.getValueRange();
        String lowerEndpoint = valueRange.lowerEndpoint();
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(sf.parse(lowerEndpoint));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int year = c.get(Calendar.YEAR);
        int beginMonth = c.get(Calendar.MONTH) + 1;
        String upperEndpoint = valueRange.upperEndpoint();
        try {
            c.setTime(sf.parse(upperEndpoint));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int endMonth = c.get(Calendar.MONTH) + 1;
        for (int i = beginMonth; i <= endMonth; i++) {
            String dateStr = String.valueOf(year) + (i < 10 ? ("0" + i) : i);
            //组装物理表名
            String tbname = logicTableName + "_" + dateStr;
            System.out.println("----------------tbname:" + tbname);
            tables.add(tbname);
        }
        return tables;
    }

}